package com.example.jwt_moudle.interceptor;

import com.example.common.util.CommonUtil;
import com.example.common.util.JsonData;
import com.example.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;

/**
 * @Description jwt拦截器
 * @Author lihw
 * @Date 2023/12/28 10:50
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 前后端分离时，前端通过这个方法刺探后台服务是否正常
        if (HttpMethod.OPTIONS.toString().equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return true;
        }
        // 获取token
        String token = request.getHeader("Authorization");
        if (StringUtils.hasLength(token)) {
            Claims claims = JwtUtil.parseToken(token);
            if (Objects.isNull(claims)) {
                CommonUtil.sendJsonMessage(response, JsonData.buildError("登录信息已失效"));
                return false;
            }

            // todo 缓存用户token信息到request/ThreadLocal
            // request.setAttribute("tokenInfo", claims);
            // threadLocal.set(xxx);


            return true;
        }


        CommonUtil.sendJsonMessage(response, JsonData.buildError("未登录"));

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
